/*******************************************************************************
 * Dreampalace
 *******************************************************************************
 * 
 * Dreampalace is a special dreamdiary which helps dreamers to understand their
 * dreams. You can find also many features in Dreampalace to learn and hold the
 * lucid state in your dreams.
 * 
 * *****************************************************************************
 *
 * Program	   : Dreampalace
 * Autor           : PRo (Peter Rogge)
 * Email           : rogge-peter@gmx.de
 * Homepage        : http://code.google.com/p/dreampalace
 * License	   : GNU General Public License 3.0
 * 
 *******************************************************************************
 * 
 * This file is part of the project Dreampalace. Dreampalace is free software:
 * you can redistribute it and/or modify it under the terms of the GNU General 
 * Public License as published by the Free Software Foundation in version 3 of
 * the License only.
 * 
 * Dreampalace is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * Dreampalace. If not, see <http://www.gnu.org/licenses/>.
 * 
 * The Dreampalace project designates this particular file as subject to the
 * "Classpath" exception as provided by the Dreampalace project in the GPL 
 * Version 3 section of the License file that accompanied this code.
 * 
 *******************************************************************************
 */
package de.pro.dreampalace.manager;

import com.zenjava.jfxflow.actvity.Activity;
import com.zenjava.jfxflow.actvity.FxmlLoader;
import com.zenjava.jfxflow.control.Browser;
import com.zenjava.jfxflow.navigation.DefaultNavigationManager;
import com.zenjava.jfxflow.navigation.Place;
import com.zenjava.jfxflow.navigation.RegexPlaceResolver;
import de.pro.dreampalace.database.api.IConnectionManager;
import de.pro.dreampalace.file.api.EFileTyp;
import de.pro.dreampalace.file.manager.api.IFileManager;
import de.pro.dreampalace.manager.api.IDreamPalaceManager;
import de.pro.dreampalace.util.api.IUtilManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;

/**
 *
 * @author Peter Rogge (PRo) <rogge-peter@gmx.de>
 */
@ServiceProvider(service=IDreamPalaceManager.class)
public class DreamPalaceManager implements IDreamPalaceManager {
    
    private Boolean isDreamStartet = Boolean.FALSE;
    
    private Stage dreamStage = null;

    @Override
    public void startWithDreaming(Stage dreamStage) {
        if (isDreamStartet) {
            return;
        }
        isDreamStartet = Boolean.TRUE;
        
        this.dreamStage = dreamStage;
        
        this.initLogger();
        this.initDataBase();
        this.initTables();
        this.initDreamApplication();
        this.initShutDownListeners();
    }
    
    private void initShutDownListeners() {
        dreamStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

            @Override
            public void handle(WindowEvent event) {
                /*
                 * TODO Check shutdown conditions
                 *  - If there are unsaved files?
                 *  - save all data
                 *  - shutdown database
                 *  - show message to dreamer -> welcome dreamer to reality :)
                 *  - close program
                 */
                try {
                    final IConnectionManager cm = Lookup.getDefault().lookup(
                            IConnectionManager.class);
                    cm.shutdownConnection();
                } catch (SQLException ex) {
                    Logger.getLogger(DreamPalaceManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    
    private void initTables() {
        final IFileManager fm = Lookup.getDefault().lookup(IFileManager.class);
        fm.checkTables();
    }
    
    private void initLogger() {
        
//        Platform.runLater(new Runnable() {
//
//            public void run() {
//                DOMConfigurator.configureAndWatch("log/log4j.xml");
//                
//                
//                Logger logger = Logger.getLogger(AwakeInYourDreams.class);
//                logger.info("START Dreampalace_v0.0.0 clear dream I wish you :)\n");
//            }
//        });
    }
    
    private void initDataBase() {
        try {
            final IConnectionManager cm = Lookup.getDefault().lookup(IConnectionManager.class);
            cm.initConnection();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DreamPalaceManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(DreamPalaceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void initDreamApplication() {
        /*
         * TODO Init dream-application
         *  - init default-gui
         * 
         *  - init overview-news
         *     - load files from the last 5 days
         *  - init archiv
         * 
         *  - init tags
         */
        final FxmlLoader loader = new FxmlLoader();
        final DefaultNavigationManager navigationManager = new DefaultNavigationManager();
        final IUtilManager um = Lookup.getDefault().lookup(IUtilManager.class);
        final Browser browser = new Browser(navigationManager,
                um.getMessage(IUtilManager.KEY_DREAMPALACE_TITLE));
        
        final String placeOverview = this.getMessage("fxml.overview"); // NOI18N
        final OverviewActivity overviewActivity = loader.load(placeOverview,
                NbBundle.getBundle(this.getClass()));
        overviewActivity.setNavigationManager(navigationManager);
        browser.getPlaceResolvers().add(new RegexPlaceResolver(placeOverview,
                overviewActivity));
        
        // Register files
        final IFileManager fm = Lookup.getDefault().lookup(IFileManager.class);
        fm.setNavigationManager(navigationManager);
        
        // Place
        Activity activity = fm.getPlace(EFileTyp.ABOUT, null);
        browser.getPlaceResolvers().add(new RegexPlaceResolver(
                EFileTyp.ABOUT.getPlace(), activity));
        
        activity = fm.getPlace(EFileTyp.LINKS, null);
        browser.getPlaceResolvers().add(new RegexPlaceResolver(
                EFileTyp.LINKS.getPlace(), activity));
        
        // PlaceEditor
        activity = fm.getPlaceEditor(EFileTyp.LINKS_EDITOR, null);
        browser.getPlaceResolvers().add(new RegexPlaceResolver(
                EFileTyp.LINKS_EDITOR.getPlace(), activity));
        
        activity = fm.getPlaceEditor(EFileTyp.NOTES_EDITOR, null);
        browser.getPlaceResolvers().add(new RegexPlaceResolver(
                EFileTyp.NOTES_EDITOR.getPlace(), activity));
        
        // Open first page
        navigationManager.goTo(new Place(placeOverview));
        
        StackPane stackPane = new StackPane();
        stackPane.getChildren().add(browser);
        
        Scene scene = new Scene(stackPane, 800, 600, Color.LIGHTSEAGREEN);
        scene.getStylesheets().add(this.getMessage("dreampalace.css")); // NOI18N
        dreamStage.centerOnScreen();
        dreamStage.setTitle(um.getMessage(IUtilManager.KEY_DREAMPALACE_TITLE_VERSION));
        dreamStage.setScene(scene);
        dreamStage.show();
    }
    
    private String getMessage(String key) {
        return NbBundle.getMessage(this.getClass(), key);
    }
}
